import { Context } from 'koa';
import { AppDataSource } from "@/config/database";

// 假设已有其他函数如login和getProfile

// 获取用户所有权限
export const getUserPermissions = async (ctx: Context) => {
    try {
        const userId = ctx.state.user?.id; // 假设用户ID存储在JWT中
        
        if (!userId) {
            ctx.status = 401;
            ctx.body = {
                code: 401,
                message: '未授权，请先登录'
            };
            return;
        }

        // 使用原生SQL查询获取用户所有权限（避免多次关联查询）
        const permissions = await AppDataSource.query(`
            SELECT DISTINCT p.id, p.name, p.code, p.description
            FROM permission p
            INNER JOIN role_permission rp ON p.id = rp.permission_id
            INNER JOIN role r ON rp.role_id = r.id
            INNER JOIN user_role ur ON r.id = ur.role_id
            WHERE ur.user_id = ?
        `, [userId]);

        // 或使用TypeORM关系查询
        /*
        const userWithPermissions = await getRepository(User)
            .createQueryBuilder('user')
            .leftJoinAndSelect('user.roles', 'roles')
            .leftJoinAndSelect('roles.permissions', 'permissions')
            .where('user.id = :userId', { userId })
            .getOne();

        // 提取权限并去重
        const permissionMap = new Map();
        if (userWithPermissions && userWithPermissions.roles) {
            userWithPermissions.roles.forEach(role => {
                if (role.permissions) {
                    role.permissions.forEach(permission => {
                        permissionMap.set(permission.id, permission);
                    });
                }
            });
        }
        const permissions = Array.from(permissionMap.values());
        */

        ctx.body = {
            code: 200,
            message: '获取权限成功',
            data: {
                permissions
            }
        };
    } catch (error) {
        console.error('获取用户权限失败:', error);
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: '服务器错误，获取权限失败'
        };
    }
};
